//
//  DKPhotoBrowser.m
//  xiaoquan
//
//  Created by 许建勇 on 15/8/31.
//  Copyright (c) 2015年 Alex. All rights reserved.
//

#import "DKPhotoBrowserCell.h"
#import "DKPhotoBrowser.h"
#import "DKCoverFlow.h"


@interface DKPhotoBrowser()<DKCoverFlowDataSource,DKCoverFlowDelegate>
#pragma mark - UI
/**
 *  滚动视图
 */
@property (nonatomic,strong) DKCoverFlow *coverFlow;

/**
 图片序号
 */
@property (nonatomic,strong) UILabel *imageIndex;

/**
 *  缓存model数据
 */
@property (nonatomic,strong) NSMutableDictionary *modelBufferDic;

/**
 *  临时新的window
 */
@property (nonatomic,strong) UIWindow *displayWindow;

#pragma mark - Parameter
@property (nonatomic,assign) NSInteger totalCount;
@end

@implementation DKPhotoBrowser
#pragma mark - Init
- (void)initParameter
{
    _currentIndex=0;
    _totalCount=0;
    self.modelBufferDic=[[NSMutableDictionary alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss) name:kPhotoBrowserDismissNotificaiton object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenNotificaiton:) name:kPhotoBrowserDismissWithoutAnimationNotificaiton object:nil];
}

- (void)initUI
{
    self.frame=[UIScreen mainScreen].bounds;
    
    //滚动视图
    _coverFlow=[[DKCoverFlow alloc] init];
    [_coverFlow setDelegate:self];
    [_coverFlow setDataSource:self];
    [_coverFlow setOrientation:DKCoverFolowOrientationHorizontal];
    [_coverFlow setCellGap:0];
    [_coverFlow setPagingEnable:NO];
    [_coverFlow.scrollView setPagingEnabled:YES];
    [_coverFlow setBackgroundColor:[UIColor blackColor]];
    [self addSubview:_coverFlow];
    
    //图片序号
    _imageIndex=[[UILabel alloc] init];
    [_imageIndex setFont:[UIFont systemFontOfSize:16.0f]];
    [_imageIndex setTextColor:[UIColor whiteColor]];
    [_imageIndex setText:@"0/0"];
    [_imageIndex setTextAlignment:NSTextAlignmentCenter];
    [_imageIndex setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.4]];
    [_imageIndex setClipsToBounds:YES];
    [self addSubview:_imageIndex];
    
    [self refreshIndex];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - Getter
- (UIWindow *)displayWindow
{
    if(_displayWindow==nil)
    {
        _displayWindow=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _displayWindow.windowLevel=UIWindowLevelStatusBar;
        _displayWindow.backgroundColor=[UIColor clearColor];
    }
    return _displayWindow;
}




#pragma mark - Layout
- (void)refreshLayout:(CGRect)frame
{
    //滚动视图
    _coverFlow.frame=CGRectMake(0,
                                0,
                                frame.size.width,
                                frame.size.height);
    
    //cell的尺寸
    [_coverFlow setCellSize:CGSizeMake(frame.size.width,
                                       frame.size.height)];
    
    //图片序号
    _imageIndex.frame=CGRectMake((frame.size.width-_imageIndex.frame.size.width)/2,
                                 20,
                                 _imageIndex.frame.size.width,
                                 _imageIndex.frame.size.height);
    
    _imageIndex.layer.cornerRadius=_imageIndex.frame.size.height/2;
}


#pragma mark - DKCoverFlowDelegate+DataSource
- (NSInteger)numberOfRowsInCoverFlow:(DKCoverFlow *)coverFlow
{
    self.totalCount=[_delegate numberOfPhotoBrowser:self];
    [self refreshIndex];
    return self.totalCount;
}

- (DKCoverFlowCell *)coverFlow:(DKCoverFlow *)coverFlow forIndex:(NSInteger)index
{
    NSString* reuseIdentifer=@"DKPhotoBrowserCell";
    DKPhotoBrowserCell *cell=[coverFlow dequeueReusableCellWithIdentifier:reuseIdentifer];
    if(!cell)
    {
        cell=[[DKPhotoBrowserCell alloc] initWithReuseIdentifier:reuseIdentifer];
    }
    
    if([_delegate respondsToSelector:@selector(photoBrowser:placeholderImageForIndex:)])
    {
        UIImage* placeHolderImage=[_delegate photoBrowser:self placeholderImageForIndex:index];
        [cell setPlaceHolderImage:placeHolderImage];
    }
    else
    {
        [cell setPlaceHolderImage:nil];
    }
    
    //放置model
    DKPhotoModel *model=[self.modelBufferDic objectForKey:[NSString stringWithFormat:@"Model:%ld",index]];
    if(model==nil)
    {
        model=[_delegate photoBrowser:self imageUrlForIndex:index];
        [self.modelBufferDic setObject:model forKey:[NSString stringWithFormat:@"Model:%ld",index]];
    }
    [cell loadPhotoModel:model];
    return cell;
}

-(void)coverFlow:(DKCoverFlow *)coverFlow didScrollToIndex:(NSInteger)index
{
    self.currentIndex=index;
    [self refreshIndex];
}

-(void)coverFlow:(DKCoverFlow *)coverFlow didScrollPassByIndex:(NSInteger)index
{
    self.currentIndex=index;
    [self refreshIndex];
}



#pragma mark - Action
/**
 *  刷新顶部下标显示
 */
- (void)refreshIndex
{
    _imageIndex.text=[NSString stringWithFormat:@"%ld/%ld",self.currentIndex+1,self.totalCount];
    CGFloat textWidth=[_imageIndex.text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
                                                     options:NSStringDrawingTruncatesLastVisibleLine
                                                  attributes:@{NSFontAttributeName:_imageIndex.font}
                                                     context:nil].size.width;
    _imageIndex.frame=CGRectMake((self.frame.size.width-textWidth-kPhotoBrowserIndexHorizonalGap*2)/2,
                                 _imageIndex.frame.origin.y,
                                 textWidth+kPhotoBrowserIndexHorizonalGap*2,
                                 20);
}




-(void)dismiss
{
    [self setHidden:YES];
    //------------------------------------------------------------------------
    //过渡动画
    DKPhotoBrowserCell *cell=(DKPhotoBrowserCell *)[_coverFlow cellForIndex:self.currentIndex];
    DKPhotoModel *model=[_delegate photoBrowser:self imageUrlForIndex:self.currentIndex];
    UIImage *shotImage=nil;
    if(cell!=nil)
    {
        shotImage=cell.imageView.image;
    }
    else
    {
        if([_delegate respondsToSelector:@selector(photoBrowser:placeholderImageForIndex:)])
        {
            shotImage=[_delegate photoBrowser:self placeholderImageForIndex:self.currentIndex];
        }
    }
    
    //动画开始rect
    CGRect fromRect=CGRectMake((self.displayWindow.frame.size.width-100)/2,
                               (self.displayWindow.frame.size.height-100)/2,
                               100,
                               100);
    //动画结束rect
    CGRect toRect=CGRectMake(self.displayWindow.frame.size.width/2,
                             self.displayWindow.frame.size.height/2,
                             0,
                             0);
    
    //调整结束rect
    if(model.rectView!=nil)
    {
        toRect=[model.rectView.superview convertRect:model.rectView.frame
                                                toView:self.displayWindow];
    }
    
    //调整开始rect
    if(cell!=nil)
    {
        fromRect=[cell.imageView.superview convertRect:cell.imageView.frame toView:self.displayWindow];
    }
    
    
    //背景
    UIView* backgroundView=[[UIView alloc] initWithFrame:self.displayWindow.bounds];
    [backgroundView setBackgroundColor:_coverFlow.backgroundColor];
    [self.displayWindow addSubview:backgroundView];
    
    //图片
    UIImageView *transitView=[[UIImageView alloc] initWithFrame:fromRect];
    [transitView setImage:shotImage];
    [transitView setContentMode:UIViewContentModeScaleAspectFill];
    [transitView setClipsToBounds:YES];
    [self.displayWindow addSubview:transitView];
    //------------------------------------------------------------------------
    [UIView animateWithDuration:kPhotoBrowserAnimationTime
                     animations:^{
                         backgroundView.backgroundColor=[UIColor clearColor];
                         transitView.frame=toRect;
                     }
                     completion:^(BOOL finished) {

                         [backgroundView removeFromSuperview];
                         [transitView removeFromSuperview];
                         [self removeFromSuperview];
                         
                         [self.displayWindow setHidden:YES];
                     }];
}



- (void)listenNotificaiton:(NSNotification *)notification
{
    if([notification.name isEqualToString:kPhotoBrowserDismissWithoutAnimationNotificaiton])
    {
        [self removeFromSuperview];
        [self.displayWindow resignKeyWindow];
    }
}



#pragma mark - API
- (void)show
{
    self.displayWindow.hidden=NO;
    
    [self.displayWindow addSubview:self];
    self.hidden=YES;
    //------------------------------------------------------------------------
    //过渡动画
    DKPhotoModel *model=[_delegate photoBrowser:self imageUrlForIndex:self.currentIndex];
    UIImage *shotImage=nil;
    if([_delegate respondsToSelector:@selector(photoBrowser:placeholderImageForIndex:)])
    {
        shotImage=[_delegate photoBrowser:self placeholderImageForIndex:self.currentIndex];
    }
    
    //动画开始rect
    CGRect fromRect=CGRectMake(self.displayWindow.frame.size.width/2,
                               self.displayWindow.frame.size.height/2,
                               0,
                               0);
    //动画结束rect
    CGRect toRect=fromRect;
    
    //调整开始rect
    if(model.rectView!=nil)
    {
        fromRect=[model.rectView.superview convertRect:model.rectView.frame
                                                toView:self.displayWindow];
    }
    
    //调整结束rect
    if(shotImage!=nil)
    {
        CGFloat scaleKey=1;
        CGSize screenSize=[UIScreen mainScreen].bounds.size;
        scaleKey=MAX(shotImage.size.width/screenSize.width, shotImage.size.height/screenSize.height);
        if(scaleKey==0)
        {
            scaleKey=1;
        }

        
        //调整imageView尺寸
        CGFloat imageWidth=shotImage.size.width/scaleKey;
        CGFloat imageHeight=shotImage.size.height/scaleKey;
        toRect=CGRectMake((screenSize.width-imageWidth)/2,
                          (screenSize.height-imageHeight)/2,
                          imageWidth,
                          imageHeight);
    }
    
    
    //背景
    UIView* backgroundView=[[UIView alloc] initWithFrame:self.displayWindow.bounds];
    [backgroundView setBackgroundColor:[UIColor clearColor]];
    [self.displayWindow addSubview:backgroundView];
    
    //图片
    UIImageView *transitView=[[UIImageView alloc] initWithFrame:fromRect];
    [transitView setImage:shotImage];
    [transitView setContentMode:UIViewContentModeScaleAspectFill];
    [transitView setClipsToBounds:YES];
    [self.displayWindow addSubview:transitView];
    //------------------------------------------------------------------------
    [UIView animateWithDuration:kPhotoBrowserAnimationTime
                     animations:^{
                         backgroundView.backgroundColor=_coverFlow.backgroundColor;
                         transitView.frame=toRect;
                     }
                     completion:^(BOOL finished) {
                         [backgroundView removeFromSuperview];
                         [transitView removeFromSuperview];
                         [self setHidden:NO];
                         [_coverFlow scrollToRow:self.currentIndex Animated:NO];
                     }];

}



/**
 *  刷新显示
 */
- (void)reloadData
{
    [self.modelBufferDic removeAllObjects];
    [_coverFlow reloadData];
}

@end
